#!/usr/bin/env bash

project=gateway-proxy-server

start() {
	status
	if [ ! $? -eq 0 ]; then
		echo "${project} is already running.."
		return 1
	fi

    nohup python gateway_proxy_server.py --port 9600 > /dev/null 2>&1  &
    nohup python gateway_proxy_uppdate.py > /dev/null 2>&1  &
    echo "${project} start success..."
}

stop() {

    # 先关闭监控脚本
    ret=`ps -ef | grep -v grep | grep -w gateway_proxy_server.py | awk '{print $2}'`
    if [ -z "${ret}" ]; then
	    echo "gateway_proxy_server.py not running.."
	else
	    kill -9 ${ret}
	fi

    # 循环去干掉进程
    while true
	do
        ret=`ps -ef | grep -v grep | grep -w gateway_proxy_uppdate.py | awk '{print $2}'`
        if [ -z "${ret}" ]; then
            echo "gateway_proxy_uppdate.py not running.."
            break
        else
            kill ${ret}
            echo "代理更新进程执行kill命令..."
        fi
        sleep 2
	done

	status
	[ $? -eq 0 ] && echo "${project} stop success..." && return 1

	echo "${project} stop fail..."
	return 0
}

restart() {
    stop
    sleep 2
    start
}

status() {
    pid=`ps -ef | grep python | grep -v grep | grep -w gateway_proxy_server.py | awk '{print $2}'`
    if [ -z ${pid} ]; then
        return 0
    fi
    echo "${pid}"

    pid=`ps -ef | grep python | grep -v grep | grep -w gateway_proxy_uppdate.py | awk '{print $2}'`
    if [ -z ${pid} ]; then
        return 0
    fi
    echo "${pid}"

	return ${pid}
}

case "$1" in
	start|stop|restart|status)
  		$1
		;;
	*)
		echo $"Usage: $0 {start|stop|status|restart}"
		exit 1
esac
